package com.crud.service.impl;

import com.crud.entity.Dept;
import com.crud.entity.DeptExample;
import com.crud.entity.Emp;
import com.crud.entity.EmpExample;
import com.crud.mapper.DeptMapper;
import com.crud.mapper.EmpMapper;
import com.crud.service.EmpService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * @author hyh
 * @date 2023/06/29 18:34:40
 */
@Service
@Transactional
public class EmpServiceImpl implements EmpService {
    @Autowired
    private EmpMapper empMapper;

    @Autowired
     private DeptMapper deptMapper;
    @Override
    public List<Emp> findAll(Integer pageNum,Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return empMapper.selectByExample(null);
    }

    @Override
    public int save(Emp emp) {
        return empMapper.insert(emp);
    }

    @Override
    public int delete(Integer id) {
        return empMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int update(Emp emp) {
        return empMapper.updateByPrimaryKeySelective(emp);
    }

    @Override
    public List<Emp> findByOther(Map<String, String> map) {
        String name = map.get("name");
        String deptName = map.get("deptName");

        Dept dept = new Dept();
        if(deptName !=null){
            DeptExample deptExample = new DeptExample();
            deptExample.or().andNameLike("%"+deptName+"%");
            List<Dept> depts =  deptMapper.selectByExample(deptExample);
             dept = depts.get(0);
            System.out.println(dept+"++++++++++++++++++++++++++++++++++++++++");
        }
        EmpExample example = new EmpExample();
        if (dept != null) {
            example.or().andNameLike("%"+name+"%").andDeptidEqualTo(dept.getId());
        }else {
            example.or().andNameLike("%"+name+"%");
        }
        Integer pageNum = Integer.valueOf(map.get("pageNum"));
        Integer pageSize = Integer.valueOf(map.get("pageSize"));
        PageHelper.startPage(pageNum, pageSize);
        List<Emp> list = empMapper.selectByExample(example);
        return list;
    }
}
